package v1

import (
	"github.com/gin-gonic/gin"
	"manager/bll"
	"manager/model"
	"manager/server/web/middleware"
	"manager/utils"
)

var Repair = &repair{}

func init() {
	// 注册路由
	RegisterRouter(Repair)
}

type repair struct{}

// Init 初始化路由
func (a *repair) Init(r *gin.RouterGroup) {
	// web 路由
	g := r.Group("/repair", middleware.Auth())
	{
		g.POST("/create", a.create)
		g.POST("/update", a.update)
		g.POST("/list", a.list)
		g.POST("/delete", a.delete)
		g.POST("/detail", a.find)
		g.POST("/recall", a.recall)

	}
	// app 路由
	appG := r.Group("app/repair", middleware.Auth())
	{
		appG.POST("/create", a.create)
		appG.POST("/update", a.update)
		appG.POST("/list", a.list)
		appG.POST("/delete", a.delete)
		appG.POST("/detail", a.find)
		appG.POST("/recall", a.recall)
	}
}

// create 创建
func (a *repair) create(c *gin.Context) {
	var (
		in  = &model.RepairCreateRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.Repair.Create(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}

// update 更新
func (a *repair) update(c *gin.Context) {
	var (
		in  = &model.RepairUpdateRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.Repair.Update(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}

// list 列表查询
func (a *repair) list(c *gin.Context) {
	var (
		in  = &model.RepairListRequest{}
		out = &model.RepairListResponse{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if out, err = bll.Repair.List(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, out)
}

// list 列表查询
func (a *repair) find(c *gin.Context) {
	var (
		in  = &model.RepairInfoRequest{}
		out = &model.RepairInfo{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if out, err = bll.Repair.Find(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, out)
}

// delete 删除
func (a *repair) delete(c *gin.Context) {
	var (
		in  = &model.RepairDeleteRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.Repair.Delete(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}

func (a *repair) recall(c *gin.Context) {
	var (
		in  = &model.RepairDeleteRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	// 撤回
	status := 3
	if err = bll.Repair.Update(c.Request.Context(), &model.RepairUpdateRequest{
		Id:     in.Id,
		Status: &status,
	}); err != nil {
		c.Error(err)
		return
	}

	// todo: 撤回后，需要修改流程
	utils.ResponseOk(c, nil)
}
